package com.jonah.executor;

import com.jonah.pojo.BoundSql;
import com.jonah.pojo.Configuration;
import com.jonah.pojo.MappedStatement;
import com.jonah.utils.GenericTokenParser;
import com.jonah.utils.ParameterMapping;
import com.jonah.utils.ParameterMappingTokenHandler;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @Author: Jonah.Chen
 * @Date: 2020/8/5 22:47
 * @Description:
 */
public class SimpleExecutor implements Executor {

    private Connection connection = null;

    @Override
    public <T> List<T> query(Configuration configuration, MappedStatement mappedStatement, Object... params) throws Exception {
        //if (Arrays.stream(params).count() > 1) {
        //    throw new RuntimeException("zj");
        //}
        PreparedStatement preparedStatement = getPreparedStatement(configuration, mappedStatement, params);

        // 5.执行sql
        ResultSet resultSet = preparedStatement.executeQuery();

        // 6.封装返回结果集
        Class<?> resultClz = getClassType(mappedStatement.getResultType());

        List<Object> resultList = new ArrayList<>();

        while (resultSet.next()) {
            Object instance = resultClz.newInstance();
            // 元数据
            ResultSetMetaData metaData = resultSet.getMetaData();
            for (int i = 1; i <= metaData.getColumnCount(); i++) {
                // 获取字段名
                String columnName = metaData.getColumnName(i);
                Object value = resultSet.getObject(columnName);
                // 反射查找结果集封装
                PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName, resultClz);
                Method writeMethod = propertyDescriptor.getWriteMethod();
                writeMethod.invoke(instance, value);
            }
            resultList.add(instance);
        }

        return (List<T>) resultList;
    }

    @Override
    public Integer update(Configuration configuration, MappedStatement mappedStatement, Object param) throws Exception {
        PreparedStatement preparedStatement = getPreparedStatement(configuration, mappedStatement, param);

        //5. 执行sql
        int executeUpdate = preparedStatement.executeUpdate();
        return executeUpdate;
    }

    private PreparedStatement getPreparedStatement(Configuration configuration, MappedStatement mappedStatement,
                                                   Object... params) throws Exception {
        // 1.注册驱动
        connection = configuration.getDataSource().getConnection();

        // 2.获取sql语句, 需要对#{}中的值进行转换存储
        BoundSql boundSql = getBoundSql(mappedStatement.getSql());

        // 3.获取预处理对象 preparedStatement
        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSql());

        // 4.设置参数
        Class<?> paramClz = getClassType(mappedStatement.getParamType());
        if (null == paramClz) {
            // 没有参数直接返回
            return preparedStatement;
        }

        List<ParameterMapping> mappingList = boundSql.getParameterMappingList();
        for (int i = 0; i < mappingList.size(); i++) {
            Object value;
            if (isBaseType(paramClz)) {
                // 基本数据类型直接设置参数
                value = params[i];
            } else {
                ParameterMapping parameterMapping = mappingList.get(i);
                String parameterName = parameterMapping.getContent();
                Object parameterObject = getParameterObject(parameterName, params);
                if (null == parameterObject) {
                    throw new RuntimeException("sql占位符参数不属于任何对象");
                }
                // 反射查找对应类并将值映射进去
                Field field = paramClz.getDeclaredField(parameterMapping.getContent());
                field.setAccessible(true);
                value = field.get(parameterObject);
            }
            preparedStatement.setObject(i+1, value);
        }
        return preparedStatement;
    }


    private Class<?> getClassType(String paramType) throws ClassNotFoundException {
        if (paramType != null) {
            return Class.forName(paramType);
        }
        return null;
    }

    /**
     * 完成对#{}的解析, 与对sql的替换
     * @param sql
     * @return
     */
    private BoundSql getBoundSql(String sql) {
        // 标记处理类, 配置标记解析器来完成对占位符的处理工作
        ParameterMappingTokenHandler tokenHandler = new ParameterMappingTokenHandler();
        GenericTokenParser genericTokenParser = new GenericTokenParser("#{", "}", tokenHandler);
        // 解析过后的sql
        String parseSql = genericTokenParser.parse(sql);
        // 解析出来的参数名称
        List<ParameterMapping> parameterMappings = tokenHandler.getParameterMappings();

        return new BoundSql(parseSql, parameterMappings);
    }

    private boolean isBaseType(Class<?> clazz) {
        if (null == clazz) {
            throw new RuntimeException("参数类型错误");
        }
        return clazz.equals(Integer.class) ||
                clazz.equals(int.class) ||
                clazz.equals(Byte.class) ||
                clazz.equals(byte.class) ||
                clazz.equals(Long.class) ||
                clazz.equals(long.class) ||
                clazz.equals(Double.class) ||
                clazz.equals(double.class) ||
                clazz.equals(Float.class) ||
                clazz.equals(float.class) ||
                clazz.equals(Character.class) ||
                clazz.equals(char.class) ||
                clazz.equals(Short.class) ||
                clazz.equals(short.class) ||
                clazz.equals(Boolean.class) ||
                clazz.equals(boolean.class);
    }


    private Object getParameterObject(String name, Object[] params) {
        for (Object param : params) {
            Field[] declaredFields = param.getClass().getDeclaredFields();
            for (Field declaredField : declaredFields) {
                String fieldName = declaredField.getName();
                if (name.equalsIgnoreCase(fieldName)) {
                    return param;
                }
            }
        }
        return null;
    }
}